package com.aisile.crowd_funding.system.controller;

import com.aisile.crowd_funding.common.utils.MD5Utils;
import com.aisile.crowd_funding.common.utils.R;
import com.aisile.crowd_funding.common.utils.StringUtils;
import com.aisile.crowd_funding.system.pojo.SysUser;
import com.aisile.crowd_funding.system.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
public class LoginController {
    @Autowired
    UserService userService;
    @RequestMapping(value={"/",""})
    public String defaultPage(){
        return "redirect:index";
    }

    @RequestMapping("login")
    public String login(){
        List<SysUser> sysUsers=userService.selectByExample(null);
        System.out.println(sysUsers);
        return "login";
    }

    @RequestMapping("index")
    public String index(){
        return "index";
    }

    @RequestMapping("loginSign")
    @ResponseBody
    public R loginSign(String username,String password){
        //校验参数
        if(StringUtils.isBlank(username)){
            return R.error("用户名不能为空");
        }
        if(StringUtils.isBlank(password)){
            return R.error("密码不能为空");
        }
        //认证
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username, MD5Utils.encrypt(password));

        try {
            subject.login(usernamePasswordToken);
        } catch (UnknownAccountException e) {
            R.error("未查询到该用户");
        }catch (LockedAccountException e) {
            R.error("用户认证失败");
        }catch (Exception e) {
            R.error("登录失败");
        }

        return R.ok();
    }
}
